package com.hjq.fcloud.app

import android.app.Activity
import android.app.Application
import android.os.Bundle
import com.hjq.fcloud.http.glide.GlideApp
import com.hjq.fcloud.utils.AppConfigUtils
import com.hjq.fcloud.utils.SdkHelper
import com.hjq.fcloud.utils.SimpleActivityLifecycleCallbacks
import com.tencent.mmkv.MMKV
import java.util.Collections

/**
 *    author : Android 轮子哥
 *    github : https://github.com/getActivity/AndroidProject-Kotlin
 *    time   : 2018/10/18
 *    desc   : 应用入口
 */
class AppApplication : Application() {

   companion object{
       @JvmField
       var mContext: AppApplication? = null
   }

    private var activityList: MutableList<Activity>? = null

    fun getInstance(): AppApplication? {
        return AppApplication.mContext
    }

    override fun onCreate() {
        super.onCreate()
        mContext = this
//         MMKV 初始化
        MMKV.initialize(this)

        if (AppConfigUtils.launchOk) {
            SdkHelper.initSdk(mContext)
        }

        activityList = Collections.synchronizedList(ArrayList())
        registerActivityLifecycleCallbacks(object : SimpleActivityLifecycleCallbacks() {
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
                activityList?.add(activity)
            }

            override fun onActivityDestroyed(activity: Activity) {
                activityList?.remove(activity)
            }

        })
    }

    open fun exit() {
        val iterator = activityList!!.iterator()
        while (iterator.hasNext()) {
            val activity = iterator.next()
            activity.finish()
        }
        activityList?.clear()
    }

    override fun onLowMemory() {
        super.onLowMemory()
        // 清理所有图片内存缓存
        GlideApp.get(this).onLowMemory()
    }

    override fun onTrimMemory(level: Int) {
        super.onTrimMemory(level)
        // 根据手机内存剩余情况清理图片内存缓存
        GlideApp.get(this).onTrimMemory(level)
    }

}